package com.lagou.cluster.service.impl;

import com.lagou.cluster.constants.SystemConstants;
import com.lagou.cluster.dto.LoginUserDTO;
import com.lagou.cluster.mapper.UserMapper;
import com.lagou.cluster.pojo.User;
import com.lagou.cluster.service.IUserService;
import com.lagou.cluster.util.SimpleMD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.UUID;

/**
 * @ProjectName: S2-2
 * @Title: UserServiceImpl
 * @Package: com.lagou.cluster.service.impl
 * @Description: 用户服务
 * @author: Ian
 * @date: 3/19/2021 11:31 AM
 * @version: V1.0.0
 * @Copyright:
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public User findByUsername(String username) {
        return userMapper.findByName(username);
    }

    @Override
    public boolean checkUser(LoginUserDTO userDTO) {
        User userInfo = findByUsername(userDTO.getUsername());
        if (userInfo == null) {
            userDTO.setMessage("用户或密码不存在");
            return false;
        }

        String password = SimpleMD5Util.getMD5(userDTO.getPassword());
        if (!password.equals(userInfo.getPassword())) {
            userDTO.setMessage("密码错误");
            return false;
        }

        userDTO.setToken(UUID.randomUUID().toString());

        // 用户信息写入Redis缓存
        redisTemplate.opsForValue().set(SystemConstants.AUTH_TOKEN + userDTO.getToken(), userInfo);


        return true;
    }
}
